<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24" >
            <a-form-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['title',{ rules: [{ required: true, message: '请输入标题！' }]}]" placeholder="请输入标题"></a-input>
            </a-form-item>
          </a-col>
            <a-col :span="24" >
              <a-form-item label="问题分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-tree-select
                  v-decorator="['questionTypeId',{ rules: [{ required: true, message: '请选择问题分类！' }]}]"
                  placeholder="请选择问题分类"
                  multiple="true"
                  :trigger-change="true"
                  dict="question_type,name,id"
                  pidValue="0"
                  pidField="parent_id">
                </j-tree-select>
              </a-form-item>
            </a-col>
          <a-col :span="24" >
              <a-form-item label="方案分类" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-tree-select
                  v-decorator="['planTypeId',{ rules: [{ required: true, message: '请选择方案分类！' }]}]"
                  placeholder="请选择方案分类"
                  multiple="true"
                  :trigger-change="true"
                  dict="plan_type,name,id"
                  pidValue="0"
                  pidField="parent_id">
                </j-tree-select>
              </a-form-item>
            </a-col>

            <a-col  :span="24" >
              <a-form-item label="标签" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <div class="global-search-wrapper" >
                  <a-auto-complete
                    :data-source="tagDataSource"
                    class="global-search"
                    @search="onSearch"
                    @select="onSelect"
                    @change="onTagChange"
                    size="large"
                    ref="tagSearch"
                    v-decorator="['tag']"
                    style="width: 100%"
                    :defaultActiveFirstOption="false"
                  >
                    <a-input

                      autocomplete="off"
                      v-model="tagInput"
                      v-decorator="['tagInput']"
                      @keydown="checkTag"
                    >
                      <a-button
                        slot="suffix"
                        style="margin-right: -12px"
                        class="search-btn"
                        size="large"
                        type="primary"
                        @click="tagAddFunction"
                      >
                        <a-icon type="search" />
                      </a-button>
                    </a-input>
                  </a-auto-complete>
                </div>

              </a-form-item>
            </a-col>
            <a-col span="6" align="right" v-show="selectedTagList && selectedTagList.length>0">
              <div class="ant-form-item-label">
                <label>已选标签</label>
              </div>
            </a-col>
            <a-col span="18">
              <a-tag closable  style="display:inline " @close="closedTag(index)"  v-for="(tag,index) in selectedTagList" :key="tag">
                {{tag}}
              </a-tag>
            </a-col>

          <a-col :span="24" >
            <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['description']" placeholder="请输入描述"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload v-decorator="['attachmentUrl']" :trigger-change="true"></j-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="视频" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-video-upload isMultiple v-decorator="['vedioUrl']"></j-video-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="大图" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['imgUrl']"></j-image-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>

  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import JTreeSelect from '@/components/jeecg/JTreeSelect'
  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JUpload from '@/components/jeecg/JUpload'
  import JVideoUpload from '@/components/jeecg/JVideoUpload'
  import JImageUpload from '@/components/jeecg/JImageUpload'
  import { questionTypeQueryByPlan,planTypeQueryByPlan,tagList,questionTagQuery,queryTagMappingByMainId } from '@/api/api'

  export default {
    name: 'PlanForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JUpload,
      JTreeSelect,
      JImageUpload,
      JVideoUpload,
    },
    data() {
      return {
        tagDataSource:[],
        selectedTagList:[],
        tagInput:'',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        demoLabelCol:{
          span:3
        },
        wideWrapperCol:{
          span:20
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        tableKeys:[ ],
        refKeys:[],



        url: {
          add: "/plan/plan/add",
          edit: "/plan/plan/edit",
          queryById: "/plan/plan/queryById",
          questionTypeMapping: {
            list: '/plan/plan/queryQuestionTypeMappingByMainId'
          },
          planTypeMapping: {
            list: '/plan/plan/queryPlanTypeMappingByMainId'
          },
          tabMapping:{
            list: '/tag/queryTagMappingByMainId'
          }
        }
      }
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      questionTypeLoad() {
        var paramter = {
          id: this.model.id
        }
        const that = this;
        const questionTypeId = [];
        questionTypeQueryByPlan(paramter).then(res=>{
          if(res.code == 200) {
            for(let i = 0; i < res.result.length; i++) {
              let item = res.result[i]
              questionTypeId.push(item.questionTypeId);
            }
            that.questionTypeId =questionTypeId.join(",");
            let fieldval = pick({"questionTypeId":that.questionTypeId},"questionTypeId")
            that.$nextTick(() => {
              that.form.setFieldsValue(fieldval)

            })

          }
        })
      },

      planTypeLoad(){
        var paramter = {
          id: this.model.id
        }
        const that = this;
        const planTypeId = [];
        planTypeQueryByPlan(paramter).then(res=>{
          if(res.code == 200) {
            for(let i = 0; i < res.result.length; i++) {
              let item = res.result[i]
              planTypeId.push(item.planTypeId);
            }
            that.planTypeId =planTypeId.join(",");
            let fieldval = pick({"planTypeId":that.planTypeId},"planTypeId")
            that.$nextTick(() => {
              that.form.setFieldsValue(fieldval)

            })

          }
        })
      },
      questionTagLoad() {
        const parameter = {
          id: this.model.id,
          mainType:2
        }
        queryTagMappingByMainId(parameter).then(res=>{
          if(res.code == 200) {
            for(var i = 0; i < res.result.length; i++) {
              var item = res.result[i]
              this.selectedTagList.push(item.tagName)
            }
          }
        })
      },
      loadTagData(){
        let that = this;
        tagList({pageSize:10000}).then(res=>{
          if(res.success){
            for(const item in res.result.records){
              that.tagDataSource.push( res.result.records[item].name);

            }
          }
        })
      },
      checkTag(e){
        if(e.keyCode ==13){
          this.tagAddFunction(e);
        }
      },
      tagAddFunction(e){
        e.stopPropagation();
        this.pushTag(this.tagInput)
        this.tagInput = ''
      },
      onTagChange(s){

      },
      onSearch(){
        if(!this.tagDataSource.length){
          this.loadTagData();
        }
      },
      pushTag(tagName){
        if(tagName !=''){
          if(this.selectedTagList.length>0){
            for(let i in this.selectedTagList){
              if(tagName == this.selectedTagList[i]){
                return ;
              }
            }
          }

          this.selectedTagList.push(tagName);
        }
      },
      onSelect(s){
        this.tagInput =s;


      },
      //键盘事件
      keyPress(ev) {

      },
      closedTag(v){
        this.selectedTagList.splice(v,1);
      },
      addBefore(){
        this.selectedTagList =[];
        this.form.resetFields()
      },
      editBefore(){
       this.addBefore();
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'title','description','attachmentUrl','vedioUrl','imgUrl')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        this.questionTypeLoad();
        this.planTypeLoad();
        this.questionTagLoad();

      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        const questionTypeMappingList = [];
        for(const questionTypeId  of main.questionTypeId.split(",")){
          questionTypeMappingList.push({"questionTypeId":questionTypeId});
        }
        const planTypeMappingList = [];
        for(const planTypeId  of main.planTypeId.split(",")){
          planTypeMappingList.push({"planTypeId":planTypeId});
        }
        const tagMappingList =  [];
        for(const index in this.selectedTagList){
          tagMappingList.push({tagName:this.selectedTagList[index]});
        }
        main.tagMappingList = tagMappingList;


        main.questionTypeMappingList  =questionTypeMappingList;
        main.planTypeMappingList = planTypeMappingList;

        return {
          ...main

        }
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          })
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
     popupCallback(row){
       this.form.setFieldsValue(pick(row,'title','description','attachmentUrl','vedioUrl','imgUrl'))
     },

    }
  }
</script>

<style scoped>
</style>